//
//  LKTaiQianViewController.m
//  Mideleague_Shop
//
//  Created by Zhiwang on 2020/6/30.
//  Copyright © 2020 Zhiwang. All rights reserved.
//

#import "LKTaiQianViewController.h"
#import "LKTaiqianShowCell.h"
#import "LKTaiQianManagerViewController.h"
#import "LKTaiqianModel.h"
@interface LKTaiQianViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UICollectionViewFlowLayout *flowLayout;
@property(nonatomic,strong)UIPageControl *pageControl;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UIImageView *bgImageView;
@end

@implementation LKTaiQianViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getCardDataWithPage];
    self.bgImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    self.bgImageView.image = [UIImage imageNamed:@"ic_coupon_qr_bg"];
    self.bgImageView.userInteractionEnabled = YES;
    [self.view addSubview:self.bgImageView];
    [self.view insertSubview:self.bgImageView atIndex:0];
    self.navigationItem.title = @"台签";
    [self setNavgationRightBtn];
    [self createCollectionUI];
    // Do any additional setup after loading the view.
}
-(void)setNavgationRightBtn{
    WS(weakSelf)
    LKBaseButton *rightBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"台签管理" titleColor:COLOR_HEX(0x333333) layercorne:13 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:[UIColor clearColor] AndActionBlock:^(UIButton * _Nonnull btn) {
        LKTaiQianManagerViewController *vc = [[LKTaiQianManagerViewController alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar
     setShadowImage:[UIImage new]];
}
-(UIImage*) imageWithColor:(UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = nil;
}
/**
 创建collectioview的布局
 */
-(void)createCollectionUI{
    WS(weakSelf)
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = viewDefualtColor;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
        if (@available(iOS 11.0, *)) {
        self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
    }
    self.collectionView.pagingEnabled = YES;
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.top.equalTo(self.view.mas_top).offset(NAVIGATION_BAR_HEIGHT + 10);
        make.bottom.equalTo(self.view.mas_bottom).offset(-160);
    }];
    self.pageControl = [[UIPageControl alloc] init];
    _pageControl.pageIndicatorTintColor = [UIColor grayColor];
    _pageControl.currentPageIndicatorTintColor = [UIColor greenColor];
    _pageControl.currentPage = 0;
    [self.view addSubview:self.pageControl];
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).offset(30);
        make.centerX.equalTo(self.view);
        make.left.equalTo(self.view).offset(100);
        make.height.mas_equalTo(30);
    }];
    LKBaseButton *saveBtn = [LKBaseButton buttonWithFrame:CGRectZero type:UIButtonTypeCustom title:@"保存相册" titleColor:[UIColor whiteColor] layercorne:25 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:yellowDefaultColor AndActionBlock:^(UIButton * _Nonnull btn) {
        NSIndexPath *index = [NSIndexPath indexPathForItem:weakSelf.pageControl.currentPage inSection:0];
        LKTaiqianShowCell *cell = (LKTaiqianShowCell *)[weakSelf.collectionView cellForItemAtIndexPath:index];
        // 设置绘制图片的大小
        UIGraphicsBeginImageContextWithOptions(cell.bounds.size, NO, 0.0);
        // 绘制图片
        [cell.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        // 保存图片到相册   如果需要获取保存成功的事件第二和第三个参数需要设置响应对象和方法，该方法为固定格式。
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }];
    [self.view addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(50);
        make.left.equalTo(self.view).offset(10);
        make.centerX.equalTo(self.view);
    }];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"LKTaiqianShowCell" bundle:nil] forCellWithReuseIdentifier:@"LKTaiqianShowCell"];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
//    self.collectionView.alwaysBounceHorizontal = YES;
}
//图片保存成功调用
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    if (error) {
        // 保存失败
        [SVProgressHUD showInfoWithStatus:@"图片保存失败"];
    } else {
        [SVProgressHUD showInfoWithStatus:@"图片保存成功"];
        // 保存成功
    }
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;

}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LKTaiqianShowCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LKTaiqianShowCell" forIndexPath:indexPath];
    cell.model = self.dataArray[indexPath.item];
    return cell;
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        return header;
    }else{
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
        return footer;
    }
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeZero;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeZero;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(WIDTH - 40, HEIGHT - NAVIGATION_BAR_HEIGHT - 160);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat pageWidth = self.collectionView.frame.size.width;
    self.pageControl.currentPage = scrollView.contentOffset.x/pageWidth;
}
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
-(void)getCardDataWithPage{
    WS(weakSelf)
    NSMutableDictionary *param = [[NSMutableDictionary alloc] initWithDictionary:@{@"page":@"0"}];
    NSString *sign = [NSString encoingWithDic:param];
    [param setObject:sign forKey:@"sign"];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyCarUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        if ([responseObject[@"code"] isEqualToString:@"success"]) {
            NSArray *dicArray = responseObject[@"data"];
            for (NSDictionary *dic in dicArray) {
                LKTaiqianModel *model = [LKTaiqianModel modelWithDictionary:dic];
                [self.dataArray addObject:model];
            }
            weakSelf.pageControl.numberOfPages = self.dataArray.count;
            [self.collectionView reloadData];
        }else{
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        }
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}
//-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
//    return UIEdgeInsetsMake(0, 20, 0, -20);
//}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
